﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
namespace DrivingAlarm.Website
{
    public class WebsiteBase : IWebsite
    {
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref  MSG_STRUCT lParam);

        public int WatchInterval { get; protected set; }
        public int WatchDay { get; protected set; }
        public string WebsiteName { get; protected set; }
        public IntPtr Hwnd_Parent { get; set; }
        private Thread ThWatch;

        public string GetPageStr(string strUrl)
        {
            string content = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
            request.Method = "GET";
            using (HttpWebResponse respone = (HttpWebResponse)request.GetResponse())
            {
                StreamReader oStreamRd = new StreamReader(respone.GetResponseStream(), Encoding.UTF8);
                content = oStreamRd.ReadToEnd();
                oStreamRd.Close();
                oStreamRd = null;
            }
            request = null;
            return content;
        }
        public void StartWatch()
        {
            if (null == ThWatch)
            {
                ThWatch = new Thread(WatchProc);
            }
            ThWatch.Start();
        }
        public void StopWatch()
        {
            if (null != ThWatch)
            {
                ThWatch.Abort();
                ThWatch = null;
            }
        }

        public void SetWatchInterval(int sec)
        {
            WatchInterval = sec ;
        }
        public void SetWatchDay(int day)
        {
            WatchDay = day;
        }
        private void WatchProc()
        {
#if DEBUG
            WatchOne();
#else
            int timeCnt = WatchInterval;
            while (true)
            {
                Thread.Sleep(1000);
                timeCnt++;
                if (timeCnt>= WatchInterval)
                {
                    timeCnt = 0;
                    try
                    {
                        WatchOne();
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
#endif
        }
        public virtual void WatchOne()
        {
            return;
        }
    }
}
